extends Node

# 关卡配置
enum LevelType {DESERT, FOREST, SNOW, VOLCANO, CHAOS}
@export var current_level_type: LevelType = LevelType.DESERT

# 敌人场景数组（按关卡类型分组）
var enemy_scenes_by_level = {
	LevelType.DESERT: [],
	LevelType.FOREST: [],
	LevelType.SNOW: [],
	LevelType.VOLCANO: [],
	LevelType.CHAOS: []
}

# 精英敌人场景数组（按关卡类型分组）
var elite_enemy_scenes_by_level = {
	LevelType.DESERT: [],
	LevelType.FOREST: [],
	LevelType.SNOW: [],
	LevelType.VOLCANO: [],
	LevelType.CHAOS: []
}

# Boss敌人场景
var boss_scenes_by_level = {
	LevelType.DESERT: null,
	LevelType.FOREST: null,
	LevelType.SNOW: null,
	LevelType.VOLCANO: null,
	LevelType.CHAOS: null
}

@onready var spawn_timer = $SpawnTimer
@onready var elite_spawn_timer = $EliteSpawnTimer
@onready var boss_spawn_timer = $BossSpawnTimer

# 生成控制变量
var base_spawn_interval = 2.0
var min_spawn_interval = 0.2
var interval_decrease_rate = 0.05  # 每波/时间间隔减少的量
var enemies_per_spawn = 1
var max_enemies_per_spawn = 10
var increase_count_interval = 15  # 每15秒增加一次数量（示例）

# 精英敌人生成控制
var elite_spawn_chance = 0.05  # 精英敌人生成几率
var elite_spawn_interval = 30.0  # 精英敌人生成间隔（秒）
var max_elite_spawn_chance = 0.3  # 最大精英敌人生成几率

# Boss生成控制
var boss_spawn_time = 300.0  # Boss生成时间（秒）
var boss_spawned = false

# 时间追踪
var time_elapsed = 0.0
var time_since_last_count_increase = 0.0

# 关卡特殊效果计时器
var level_effect_timer = 0.0
var level_effect_interval = 45.0  # 关卡特殊效果触发间隔（秒）

# 信号
signal level_effect_triggered(effect_type)
signal boss_spawned(boss_type)

func _ready():
	# 加载所有敌人场景
	load_enemy_scenes()
	
	# 初始化计时器
	spawn_timer.wait_time = base_spawn_interval
	spawn_timer.start()
	
	elite_spawn_timer.wait_time = elite_spawn_interval
	elite_spawn_timer.start()
	
	boss_spawn_timer.wait_time = boss_spawn_time
	boss_spawn_timer.one_shot = true
	boss_spawn_timer.start()

func _process(delta):
	time_elapsed += delta
	time_since_last_count_increase += delta
	level_effect_timer += delta
	
	# 逐渐减少生成间隔
	var current_interval = max(min_spawn_interval, base_spawn_interval - (time_elapsed * interval_decrease_rate * 0.1))
	spawn_timer.wait_time = current_interval
	
	# 逐渐增加每次生成的敌人数量
	if time_since_last_count_increase >= increase_count_interval:
		enemies_per_spawn = min(max_enemies_per_spawn, enemies_per_spawn + 1)
		time_since_last_count_increase = 0.0
		print("增加每次生成的敌人数量至: ", enemies_per_spawn)
		
		# 同时增加精英敌人生成几率
		elite_spawn_chance = min(max_elite_spawn_chance, elite_spawn_chance + 0.02)
	
	# 触发关卡特殊效果
	if level_effect_timer >= level_effect_interval:
		level_effect_timer = 0.0
		trigger_level_effect()

func load_enemy_scenes():
	# 沙漠关卡敌人
	enemy_scenes_by_level[LevelType.DESERT] = [
		preload("res://DesertSlime.tscn"),
		preload("res://DesertScorpion.tscn"),
		preload("res://DesertSkeleton.tscn")
	]
	elite_enemy_scenes_by_level[LevelType.DESERT] = [
		preload("res://EliteDesertWorm.tscn"),
		preload("res://EliteDesertMummy.tscn")
	]
	boss_scenes_by_level[LevelType.DESERT] = preload("res://DesertLord.tscn")
	
	# 森林关卡敌人
	enemy_scenes_by_level[LevelType.FOREST] = [
		preload("res://ForestGoblin.tscn"),
		preload("res://ForestSpider.tscn"),
		preload("res://ForestWolf.tscn")
	]
	elite_enemy_scenes_by_level[LevelType.FOREST] = [
		preload("res://EliteForestTroll.tscn"),
		preload("res://EliteForestEntwife.tscn")
	]
	boss_scenes_by_level[LevelType.FOREST] = preload("res://ForestGuardian.tscn")
	
	# 雪山关卡敌人
	enemy_scenes_by_level[LevelType.SNOW] = [
		preload("res://SnowWolf.tscn"),
		preload("res://SnowGolem.tscn"),
		preload("res://IceElemental.tscn")
	]
	elite_enemy_scenes_by_level[LevelType.SNOW] = [
		preload("res://EliteSnowYeti.tscn"),
		preload("res://EliteIceDragon.tscn")
	]
	boss_scenes_by_level[LevelType.SNOW] = preload("res://FrostGiant.tscn")
	
	# 火山关卡敌人
	enemy_scenes_by_level[LevelType.VOLCANO] = [
		preload("res://LavaSlime.tscn"),
		preload("res://FireElemental.tscn"),
		preload("res://VolcanoLizard.tscn")
	]
	elite_enemy_scenes_by_level[LevelType.VOLCANO] = [
		preload("res://EliteLavaTitan.tscn"),
		preload("res://EliteFireDragon.tscn")
	]
	boss_scenes_by_level[LevelType.VOLCANO] = preload("res://VolcanoHeart.tscn")
	
	# 混沌关卡敌人（包含所有精英敌人）
	enemy_scenes_by_level[LevelType.CHAOS] = []
	elite_enemy_scenes_by_level[LevelType.CHAOS] = []
	
	# 将所有普通敌人添加到混沌关卡
	for level_type in [LevelType.DESERT, LevelType.FOREST, LevelType.SNOW, LevelType.VOLCANO]:
		for enemy in enemy_scenes_by_level[level_type]:
			enemy_scenes_by_level[LevelType.CHAOS].append(enemy)
	
	# 将所有精英敌人添加到混沌关卡
	for level_type in [LevelType.DESERT, LevelType.FOREST, LevelType.SNOW, LevelType.VOLCANO]:
		for elite in elite_enemy_scenes_by_level[level_type]:
			elite_enemy_scenes_by_level[LevelType.CHAOS].append(elite)
	
	boss_scenes_by_level[LevelType.CHAOS] = preload("res://ChaosGuardian.tscn")

func _on_spawn_timer_timeout():
	spawn_enemies(false)  # 生成普通敌人

func _on_elite_spawn_timer_timeout():
	# 根据几率决定是否生成精英敌人
	if randf() < elite_spawn_chance:
		spawn_enemies(true)  # 生成精英敌人

func _on_boss_spawn_timer_timeout():
	if not boss_spawned:
		spawn_boss()

func spawn_enemies(is_elite):
	var player = get_tree().get_first_node_in_group("player")
	if not player:
		return  # 如果玩家不存在，不生成敌人
	
	var enemy_list = elite_enemy_scenes_by_level[current_level_type] if is_elite else enemy_scenes_by_level[current_level_type]
	if enemy_list.is_empty():
		return  # 如果没有敌人场景定义，不生成敌人
	
	var viewport_rect = get_viewport().get_visible_rect()
	var spawn_radius = (viewport_rect.size.x + viewport_rect.size.y) / 2.0  # 视图外的半径
	var enemies_container = get_tree().get_root().get_node("Main/Enemies")  # 获取容器节点
	
	var spawn_count = 1 if is_elite else enemies_per_spawn  # 精英敌人一次只生成一个
	
	for i in range(spawn_count):
		# 选择敌人类型
		var enemy_scene = enemy_list.pick_random()
		
		# 计算生成位置（屏幕外）
		var angle = randf_range(0, TAU)  # TAU是2 * PI
		var spawn_offset = Vector2(cos(angle), sin(angle)) * spawn_radius
		var spawn_position = player.global_position + spawn_offset
		
		# 实例化并添加敌人
		var enemy_instance = enemy_scene.instantiate()
		enemies_container.add_child(enemy_instance)
		enemy_instance.global_position = spawn_position
		
		# 如果是精英敌人，设置其属性
		if is_elite:
			enemy_instance.is_elite = true
			enemy_instance.scale_stats(2.5)  # 增强精英敌人属性
			print("生成精英敌人: ", enemy_instance.name)
		else:
			# 随着时间增加普通敌人的属性
			var time_scale = min(3.0, 1.0 + time_elapsed / 300.0)  # 最多增强3倍
			enemy_instance.scale_stats(time_scale)

func spawn_boss():
	var player = get_tree().get_first_node_in_group("player")
	if not player:
		return  # 如果玩家不存在，不生成Boss
	
	var boss_scene = boss_scenes_by_level[current_level_type]
	if not boss_scene:
		return  # 如果没有Boss场景定义，不生成Boss
	
	var enemies_container = get_tree().get_root().get_node("Main/Enemies")  # 获取容器节点
	
	# 计算生成位置（屏幕外但较近）
	var viewport_rect = get_viewport().get_visible_rect()
	var spawn_radius = (viewport_rect.size.x + viewport_rect.size.y) / 3.0  # 比普通敌人更近
	var angle = randf_range(0, TAU)
	var spawn_offset = Vector2(cos(angle), sin(angle)) * spawn_radius
	var spawn_position = player.global_position + spawn_offset
	
	# 实例化并添加Boss
	var boss_instance = boss_scene.instantiate()
	enemies_container.add_child(boss_instance)
	boss_instance.global_position = spawn_position
	boss_instance.is_boss = true
	
	# 标记Boss已生成
	boss_spawned = true
	
	# 发出信号
	emit_signal("boss_spawned", current_level_type)
	
	print("生成Boss: ", boss_instance.name)

func trigger_level_effect():
	match current_level_type:
		LevelType.DESERT:
			# 沙尘暴效果
			emit_signal("level_effect_triggered", "sandstorm")
			print("触发沙尘暴效果")
		LevelType.FOREST:
			# 生命之泉效果
			emit_signal("level_effect_triggered", "healing_spring")
			print("触发生命之泉效果")
		LevelType.SNOW:
			# 暴风雪效果
			emit_signal("level_effect_triggered", "blizzard")
			print("触发暴风雪效果")
		LevelType.VOLCANO:
			# 火山喷发效果
			emit_signal("level_effect_triggered", "eruption")
			print("触发火山喷发效果")
		LevelType.CHAOS:
			# 随机选择一种效果
			var effects = ["sandstorm", "healing_spring", "blizzard", "eruption", "reality_warp"]
			var effect = effects.pick_random()
			emit_signal("level_effect_triggered", effect)
			print("触发混沌效果: ", effect)

func set_level_type(level_type):
	current_level_type = level_type
	
	# 重置Boss生成状态
	boss_spawned = false
	boss_spawn_timer.start()
	
	# 调整关卡特定参数
	match level_type:
		LevelType.DESERT:
			base_spawn_interval = 2.0
			elite_spawn_chance = 0.05
			level_effect_interval = 45.0
		LevelType.FOREST:
			base_spawn_interval = 1.8
			elite_spawn_chance = 0.07
			level_effect_interval = 40.0
		LevelType.SNOW:
			base_spawn_interval = 1.6
			elite_spawn_chance = 0.09
			level_effect_interval = 35.0
		LevelType.VOLCANO:
			base_spawn_interval = 1.4
			elite_spawn_chance = 0.12
			level_effect_interval = 30.0
		LevelType.CHAOS:
			base_spawn_interval = 1.2
			elite_spawn_chance = 0.15
			level_effect_interval = 25.0
	
	# 重置计时器
	spawn_timer.wait_time = base_spawn_interval
	elite_spawn_timer.wait_time = elite_spawn_interval
	
	print("设置关卡类型为: ", LevelType.keys()[level_type])
